<?php
/**
 * 外部接口公共类
 */

class apiHandler {
	public $gateUrl;   //网关地址
	
	public $key;       //密钥
	
	public $parameters;//请求参数
	
	function __construct() {
		$this->gateUrl = '';
		$this->parameters = array();
	}
	
	/**
	 * 接收返回参数
	 */
	public function receiveParameter() {
		$params = array();
		if (!empty($_GET)) {
			foreach ($_GET as $k => $v) {
				$params[$k] = $v;
			}
		}
		if (!empty($_POST)) {
			foreach ($_POST as $k => $v) {
				$params[$k] = $v;
			}
		}
		if (!empty($params))
			$this->setParamsArray($params);
	}
	
	/**
	 * 根据键值和值保存参数
	 */
	public function setParameter($parameter, $parameterValue) {
		$this->parameters[$parameter] = $parameterValue;
	}
	
	/**
	 * 把一个数组保存到对象parameters属性里
	 *
	 * @param array $paramsArray
	 */
	public function setParamsArray($paramsArray) {
		$this->parameters = $paramsArray;
	}
	
	/**
	 * 根据key获得参数数值
	 */
	public function getParameter($parameter) {
		if (isset($this->parameters[$parameter]))
			return $this->parameters[$parameter];
		return null;
	}
	
	/**
	 * 获取所有参数
	 * @return array
	 */
	public function getAllParameters() {
		return $this->parameters;
	}
	
	/**
	 *设置入口地址,不包含参数值
	 */
	public function setGateURL($gateUrl) {
		$this->gateUrl = $gateUrl;
	}
	
	/**
	 * 获取密钥
	 */
	public function getKey() {
		return $this->key;
	}
	
	/**
	 * 设置密钥
	 */
	public function setKey($key) {
		$this->key = $key;
	}
	
	/**
	 * 联合登录
	 *
	 * @param unknown_type $params
	 * @param unknown_type $dbca
	 * @return unknown
	 */
	public function unionLogin($params, &$G_SHOP) {
		//实例化通行证类
//		$permit = new Permit();
		
		//实例化客户类
		$customerHandler = new customerHandler($G_SHOP->DBCA);
		
		//网站客户登录
		$ret_val = $customerHandler->getCustomerInfo($params);

		//网站用户不存在，则在网站新注册用户
		if (empty($ret_val)) {
			//在网站注册新用户
			$ret_val = $customerHandler->addCustomer($params);
			if ($ret_val['code'] != 200) {
				return false;
			}
			
			$ret_val[0] = $ret_val['data'];
		} elseif (!is_array($ret_val)) {
			return false;
		}

		$customer_array = array(
            'pcustID' => $ret_val[0]['pcustID'],
            'custID' => $ret_val[0]['custID'],
            'email' => $ret_val[0]['email'],
            'custType' => $ret_val[0]['custType']
        );
		$this->checkin($customer_array,$G_SHOP);
		return true;
	}
	
	/**
	 * 使用get方式取信息
	 *
	 * @param string $url URL地址
	 * @param string $callbackType 返回值类型
	 */
	public function getMethod($url, $callbackType='json') {
		
		//获取信息
		$response = file_get_contents($url);
		if ($response === false || empty($response))
			return 0;
			
		//过滤特殊字符
		$response = &str_replace('\x3C','<',$response);
		
		if ($callbackType == 'callback') {
			
			if (strpos($response, "callback") !== false) {
				$lpos = strpos($response, "(");
				$rpos = strrpos($response, ")");
				$response  = substr($response, $lpos + 1, $rpos - $lpos -1);
				return json_decode($response);
			} else {
				$params = array();
				parse_str($response, $params);
				return $params;
			}
			
		} else {
			
			return json_decode($response);
			
		}
		
		
		
	}
	
	/**
	 * 进行登录状态修改
	 *
	 * @param unknown_type $customer_array
	 * @return unknown
	 */
	public function checkin( $customer_array,&$G_SHOP) {
	    $customerHandler = new customerHandler( $G_SHOP->DBCA );
	    $now_time = $G_SHOP->sys_datetime;
	
	    //更新用户最后登录时间和IP地址
	    $cust_obj = new entity('cust_master');
	    $cust_obj->pcustID = $customer_array['pcustID'];
	    if ($G_SHOP->DBCA->fetch($cust_obj)) {
	        $cust_obj->lastLogin = $now_time;
	        $cust_obj->IPPort = $G_SHOP->remoteIP.':'.$G_SHOP->remotePort;
	        $G_SHOP->DBCA->save($cust_obj);
	    }

	    //添加SESSION
	    if (!$login_session = $G_SHOP->sessionCache_get( 'LOGINSESSION' ))
	        $login_session = array();
	        
	    $login_session['pcustID'] = $customer_array['pcustID'];
	    $login_session['custID'] = $customer_array['custID'];
	    $login_session['email'] = $customer_array['email'];
	    
	    if ($customer_array['custType'] == 4) {
	        $login_session['guest'] = 1;
	        $G_SHOP->sessionCache_set( 'LOGINSESSION', $login_session, G_LOGINSESSION_TIMEOUT );
	        return true;
	
	    } else {
	        //查询会员最后一次购买记录
	        $sess_log = $customerHandler->searchCustBuyLog( $customer_array['pcustID'] );
	
	        $G_SHOP->sessionCache_set( 'CUST_BUY_LOG', $sess_log, G_LOGINSESSION_TIMEOUT );
	        $login_session['guest'] = 0;
	        $G_SHOP->sessionCache_set( 'LOGINSESSION', $login_session, G_LOGINSESSION_TIMEOUT );
	    }
	    //客户未登录时的购物车
	    $old_bill_array = $G_SHOP->sessionCache_get('shop_cart');
	    if (empty($old_bill_array))
	        return true;

	    $old_cart =& $old_bill_array['goods'];
	    if (empty($old_cart))
	        return true;

	    //在客户登录时把未登录时的购物车合并到客户上次登录时的购物车。
	    //同时删除未登录时的购物车
	
	    //客户上次登录时的购物车数据
	    $bill_array = $G_SHOP->sessionCache_get('shop_cart_' . $customer_array['pcustID'], true);

	    if (!$bill_array) {
	        $bill_array = array(
	
	            'bill_no' => null,
	
	            'bill_status' => 0,
	
	            'change_time' => null,
	
	            'message' => null,
	
	            'goods' => array(),
	
	            'master' => array()
	
	        );
	    }
	
	    //合并普通商品
	    if (isset($old_cart['general']) && !empty($old_cart['general'])) {
	        foreach ($old_cart['general'] as $postID => &$goods) {
	            if (isset($bill_array['goods']['general'][$postID])) {
	                $bill_array['goods']['general'][$postID]['goodsAmount'] += $goods['goodsAmount'];
	            } else {
	                $bill_array['goods']['general'][$postID] = $goods;
	            }
	        }
	    }
	    
	    if (isset($old_cart['gift']) && !empty($old_cart['gift'])) {
	        foreach ($old_cart['gift'] as $id => &$gift) {
	            if (isset($bill_array['goods']['gift'][$id])) {
	                $bill_array['goods']['gift'][$id]['goodsAmount'] += $gift['goodsAmount'];
	            } else {
	                $bill_array['goods']['gift'][$id] = $gift;
	            }
	        }
	    }

	    $bill_array['change_time'] = time();
	    $G_SHOP->sessionCache_set('shop_cart_' . $customer_array['pcustID'], $bill_array, G_SHOPPINGCART_TIMEOUT, true);
	    $G_SHOP->sessionCache_remove('shop_cart');
	    return true;
	}
	
}
?>